import { CheckAns } from "./CheckAns";

namespace LeetCode0643FindMaxAverage {

    // 直接计算
    function findMaxAverage(nums: number[], k: number): number {
        // 检查异常输入
        if (!nums || !k || nums.length < k) return 0;
        // 先算总值，除法最后计算
        let avgMax: number = 0;
        nums.slice(0, k).forEach(v => { avgMax += v; });
        let avgTemp = avgMax;
        for (let i = k; i < nums.length; i++) {
            // 计算push数值与pop数值的差值
            const delta: number = nums[i] - nums[i - k];
            avgTemp += delta;
            if (avgTemp > avgMax)
                avgMax = avgTemp;
        }
        return avgMax / k;
    };

    // test
    const testData: { ary: number[], k: number, ans: number }[] = [
        { ary: [1, 3, -1, -3, 5, 3, 6, 7], k: 3, ans: 5.333333333333333 },
        { ary: [1, 12, -5, -6, 50, 3], k: 4, ans: 12.75 }
    ];
    for (const data of testData) {
        const ans = findMaxAverage(data.ary, data.k);
        CheckAns(data, ans);
    }

}